import urllib.request
import urllib.parse



url ='https://m.douban.com/rexxar/api/v2/subject/recent_hot/movie?start=0&limit=20'
# url = 'https://m.douban.com/rexxar/api/v2/subject/recent_hot/movie?start=20&limit=20'
# url = 'https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&start=0&limit=20'

header = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
    'Cookie': 'bid=yw9rll5OvfM; ll="118201"; __utmc=30149280; __utmz=30149280.1757813764.3.3.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; _vwo_uuid_v2=D1CFD0D8D2730FED07EEC00918A408470|1de61df608b2316f02ae53cbd1aa47de; ap_v=0,6.0; __utma=30149280.789360093.1735923832.1757813764.1757838262.4; __utmt_douban=1; __utmb=30149280.1.10.1757838262',
    'accept': 'application/json, text/plain, */*',
    # 'accept-language': 'zh-CN,zh;q=0.9',
    # 'cache-control': 'no-cache',
    # 'origin': 'https://movie.douban.com',
    'referer': 'https://movie.douban.com/explore'

}

request = urllib.request.Request(url=url,headers=header)
response = urllib.request.urlopen(request)
html = response.read().decode('utf-8')
print(type(html))

import json

obj = json.loads(html)
print(json.dumps(obj, ensure_ascii=False, indent=2))

# open('douban.json','w',encoding='utf-8')
# with open('douban.json','w',encoding='utf-8')as fp:
#     fp.write(html)

# 方法1：使用 json.dump() 直接写入文件（推荐）
with open('douban.json', 'w', encoding='utf-8') as fp:
    json.dump(obj, fp, ensure_ascii=False, indent=2)

# with open('douban.json', 'w', encoding='utf-8') as fp:
#     readable_json = json.dumps(obj, ensure_ascii=False, indent=2)
#     fp.write(readable_json)